<template>
  <el-row>

    <el-row style="margin: 20px 0px 10px 0px">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/bashbord' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>集群管理</el-breadcrumb-item>
        <el-breadcrumb-item>{{tabName}}</el-breadcrumb-item>
      </el-breadcrumb>
    </el-row>

    <el-row>
      <el-tabs v-model="first" @tab-click="handleClick">
        <el-tab-pane label="概览" name="gl">
          <div style="width:97.5%;display:flex;flex-direction:row;align-items:center;justify-content:flex-end;">
            <el-select size="small" style="width:100px;margin-right:10px;" clearable v-model="time" placeholder="刷新时间" @change="changeTime">
              <el-option v-for="(item,index) in selectTime" :key="index" :label="item.label" :value="item.value"></el-option>
            </el-select>

            <el-select size="small" style="width:140px;" multiple v-model="chart" placeholder="选择图表">
              <el-option v-for="item in selectChart" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </div>

          <div style="width:100%;display:flex;flex-direction:row;justify-content:space-evenly">

            <div style="width:25%;display:flex;flex-direction:column;">

              <el-card style="width:95%;margin:10px;" v-loading="loadingData">
                <el-row>
                  <el-col :span="1">
                    <div style="width: 4px;height: 17px;background-color: #409EFF;"></div>
                  </el-col>
                  <el-col :span="8" style="line-height: 17px">基本信息</el-col>
                </el-row>
                <el-row class="row">
                  <el-col :span="14" class="color">{{essentialInformation.clusterName!==null?essentialInformation.clusterName:'openlookeng'}}</el-col>
                  <el-col :span="10">
                    <el-select size="mini" style="width:100px;" v-model="value" clearable placeholder="操作" @change="operation">
                      <el-option v-for="(item,index) in select" :key="index" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                  </el-col>
                </el-row>
                <el-row class="row">
                  <el-col :span="14" class="color">版本</el-col>
                  <el-col :span="10" class="font">{{essentialInformation.clusterVer}}</el-col>
                </el-row>
                <el-row class="row">
                  <el-col :span="14" class="color">内存</el-col>
                  <el-col :span="10" class="font">{{essentialInformation.memory}}</el-col>
                </el-row>
                <el-row class="row">
                  <el-col :span="14" class="color">CPU</el-col>
                  <el-col :span="10" class="font">{{essentialInformation.cpu}}</el-col>
                </el-row>
                <el-row class="row">
                  <el-col :span="14" class="color">实例</el-col>
                  <el-col :span="10" class="font">{{essentialInformation.example}}</el-col>
                </el-row>
                <el-row class="row">
                  <el-col :span="14" class="color">运行时长</el-col>
                  <el-col :span="10" class="font">{{essentialInformation.uptime}}</el-col>
                </el-row>
                <el-row class="row" v-for="(item,index) in essentialInformation.address" :key="index">
                  <el-col :span="14" class="color">访问地址</el-col>
                  <el-col :span="10" class="font"><a style="color: #409EFF;text-decoration: none" :href="item" target="_blank">{{item}}</a></el-col>
                </el-row>
              </el-card>

              <el-card style="width:95%;margin:10px;" v-loading="loadingData">
                <el-row>
                  <el-col :span="1">
                    <div style="width: 4px;height: 17px;background-color: #409EFF;"></div>
                  </el-col>
                  <el-col :span="3" style="line-height: 17px;margin-bottom:5px;">角色</el-col>
                </el-row>
                <el-row>
                  <el-table :data="roleData" :header-cell-style="{'background-color':'#F5F5F5','color':'#333333 ','font-size':'12px','text-align':'center','padding':'0','height':'10px','line-height':'10px'}">
                    <el-table-column align="center" label="角色名称">
                      <template slot-scope="scope">
                        <span :style="{'color':'#409EFF'}">{{scope.row.name.toLowerCase()}}</span>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" prop="state" label="状态" width="175">
                      <template slot-scope="scope">
                        <div style="width: 8px;height: 8px;background-color: #409EFF;border-radius: 50%;display:inline-block"></div>
                        <div style="display:inline-block">运行中</div>
                        <div style="display: inline-block">{{scope.row.run}}</div>
                        <div style="width: 8px;height: 8px;background-color: red;border-radius: 50%;display:inline-block;"></div>
                        <div style="display:inline-block">已停止</div>
                        <div style="display: inline-block">{{scope.row.close}}</div>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-row>
              </el-card>
            </div>

            <div style="width:75%;display:flex;flex-direction:row;flex-wrap:wrap;">

              <el-card style="width:47.5%;height:367px;margin:10px;" v-show="showCpu" v-loading="loadingData">
                <el-row>
                  <el-col :span="1">
                    <div style="width: 4px;height: 17px;background-color: #409EFF;"></div>
                  </el-col>
                  <el-col :span="8" style="line-height: 17px">集群CPU使用率</el-col>
                </el-row>
                <el-row>
                  <div style="width: 100%;height: 350px" id="cpuUtilization"></div>
                </el-row>
              </el-card>

              <el-card style="width:47.5%;height:367px;margin:10px;" v-show="showMemory" v-loading="loadingData">
                <el-row>
                  <el-col :span="1">
                    <div style="width: 4px;height: 17px;background-color: #409EFF;"></div>
                  </el-col>
                  <el-col :span="5" style="line-height: 17px">集群内存使用率</el-col>
                </el-row>
                <el-row>
                  <div style="width:100%;height:350px;" id="memoryUsage"></div>
                </el-row>
              </el-card>

            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="实例" name="slqk">
          <nodelist></nodelist>
        </el-tab-pane>

        <el-tab-pane label="配置" name="pz">
          <el-row type="flex" justify="end" v-loading="loading">
            <el-col :span="1">
              <el-button class="btn" @click="changeClassState('restart')">启动</el-button>
            </el-col>
            <el-col :span="1">
              <el-button class="btn" @click="changeClassState('stop')">停止</el-button>
            </el-col>
            <!-- <el-col :span="1">
              <el-button class="btn" @click="updateCluster">升级</el-button>
            </el-col> -->
            <el-col :span="1">
              <el-button class="btn" @click="remove">卸载</el-button>
            </el-col>
            <el-col :span="1">
              <el-button class="btn" @click="changeClassState('restart')">重启</el-button>
            </el-col>
          </el-row>
          <el-row>
            <config :showButton="'true'"></config>
          </el-row>
          <el-dialog :visible.sync="dialogVisible" v-model="dialogVisible" title="卸载集群" width="540px"
                     @closed="closeDelDia" v-loading="loading">
            <el-checkbox v-model="removeDirectory" label="卸载集群是否同步删除目录？" size="large"></el-checkbox>
            <template #footer>
              <div class="adv_del">
                <el-button @click="dialogVisible = false,value = ''">取消</el-button>
                <el-button type="primary" @click="removeColonyOrNode">确认</el-button>
              </div>
            </template>
          </el-dialog>
        </el-tab-pane>
      </el-tabs>
    </el-row>

    <div>
      <el-dialog :visible.sync="dialogVisible" v-model="dialogVisible" title="卸载集群" width="540px" @closed="closeDelDia" v-loading="loading">
        <el-checkbox v-model="removeDirectory" label="卸载集群是否同步删除目录？" size="large"></el-checkbox>
        <template #footer>
          <div class="adv_del">
            <el-button @click="dialogVisible = false,value = ''">取消</el-button>
            <el-button type="primary" @click="removeColonyOrNode">确认</el-button>
          </div>
        </template>
      </el-dialog>
    </div>

    <el-dialog :visible.sync="updateStated" width="725px" v-loading="updateloading" append-to-body>
      <div>
        <span class="updateFont">升级方式</span>
        <el-select class="add_clu_input" style="width:90px;" @change="changeWay" v-model="updategradeWay" placeholder="请选择升级方式">
          <el-option v-for="item in updategradeWays" :key="item.value" :label="item.label" :value="item.value" ></el-option>
        </el-select>
      </div>
      <div class="installPackage" style="display:flex;line-height:40px">
        <span class="updateFont2">{{updategradeWay==2?"安装包":"版本号"}}</span>
        <el-select class="add_clu_input" @focus="updatePackageList(updategradeWay)" v-model="updatefileId" :placeholder="updategradeWay==2?'请选择安装包':'请选择版本号'">
          <el-option v-for="item in updatepackageFileList" :key="item.id" :label="item.version" :value="item.id"></el-option>
        </el-select>
         <i @click="showUploadPackage" class="iconfont icon-shangchuan shangchuanSty" v-if="updategradeWay ==2"></i>
      </div>
      <div class="installBtns">
        <el-button @click="updateStated=false;updateloading=false">取 消</el-button>
        <el-button type="primary" style="margin-left: 50px;" @click="updateState">确 定</el-button>
      </div>
    </el-dialog>
    <uploadPackage v-if="uploadVis" @closeAfter="closeAfter"></uploadPackage>
  </el-row>
</template>
<script>
  import {doGet, doPost} from '@/api/index.js'
  import nodelist from '@/view/node/list'
  import config from '@/view/config/config'
  import * as echarts from 'echarts'
  import pubsub from 'pubsub-js'
  import uploadPackage from '@/components/upload/uploadPackage'
  export default {
    props: {},
    name: 'cluster-detail-new',
    components: {
      'nodelist': nodelist,
      'config': config,
      uploadPackage
    },
    data() {
      return {
        uploadVis:false,
        updatepackageFileList:[],
        updatefileId:'',
        updategradeWays:[{label:'在线',value:'1'},{label:'离线',value:'2'}],
        updategradeWay:'',
        updateloading:false,
        updateStated:false,
        removeDirectory: false,
        dialogVisible: false,
        loading: false,
        loadingData:false,
        tabName: '概览',
        disk:
        {
          time: [],
          percentage: []
        },
        memory:
        {
          time: [],
          percentage: []
        },
        cpu:
        {
          time: [],
          percentage: []
        },
        //role information
        roleData: [],
        //basic information
        essentialInformation:
        {
          'clusterName': '- -',
          'clusterVer': '- -',
          'memory': '- -',
          'cpu': '- -',
          'example': '- -',
          'address': [],
          'nodeItem': ''
        },
        selectTime:
        [
          {
            value: '0',
            label: '实时'
          },
          {
            value: '1',
            label: '1小时'
          },
          {
            value: '2',
            label: '2小时'
          },
          {
            value: '3',
            label: '6小时'
          },
          {
            value: '4',
            label: '12小时'
          },
          {
            value: '5',
            label: '1天'
          },
          {
            value: '6',
            label: '1周'
          },
          {
            value: '7',
            label: '1月'
          }
        ],
        time: '0',
        selectChart:
        [
          {
            value: 'cpu',
            label: '集群CPU使用率'
          },
          {
            value: 'memory',
            label: '集群内存使用率'
          },
        ],
        chart: [],
        select:
        [
          {
            value: 'start',
            label: '启动'
          },
          {
            value: 'stop',
            label: '停止'
          },
          {
            value: 'upgrade',
            label: '升级'
          },
          {
            value: 'uninstall',
            label: '卸载'
          },
          {
            value: 'restart',
            label: '重启'
          }
        ],
        value: '',
        catalogName: '',
        first: 'gl',
        clock:null,
        timer:true,
        memoryEcharts:null,
        cpuEcharts:null,
        cpuResultList:[],
        memoryResultList:[],
      }
    },

    mounted()
    {
      if (this.$route.query.tab)
      {
        let obj={name:this.$route.query.tab};
        this.handleClick(obj);
      }

      this.loadingData = true;
      this.queryClusterItem();
      this.memoryEcharts = echarts.init(document.getElementById('memoryUsage'), null);
      this.cpuEcharts = echarts.init(document.getElementById('cpuUtilization'), null);

      this.clock=setInterval(()=>{
        if(this.timer){
          this.queryClusterItem2();
        }
        this.getEchartsData();
      },1000);
    },

    beforeDestroy()
    {
      clearInterval(this.clock);
      this.clock=null;
    },

    methods:{
      changeWay(){
        this.updatepackageFileList=[];
      },
      closeAfter(flag){
        this.uploadVis=flag;
      },
      showUploadPackage() {
        this.uploadVis = true
      },
      //open uninstall dialog
      remove() {
        this.dialogVisible = true;
      },
      //uninstall cluster
      removeColonyOrNode()
      {
        this.loading = true;
        let url = '/sys_openlookeng_cluster/removeColonyOrNode';
        let obj = {
          'state': 'stop',
          'nodeIds': [],
          'removeDirectory': this.removeDirectory
        };
        doPost(url, obj).then(res =>
        {
          if (res.data.code == 0)
          {
            this.loading = false;
            this.dialogVisible = false;
            this.$message.success(res.data.msg);
            //if installation success,go to configuration page
            this.$router.push('/guide')
          }
        });
      },
      //start,shut down,restart cluster
      //upgrade
      updateCluster() {},
      closeDelDia() {
        this.value = '';
      },
      //query basic information,role
      queryClusterItem()
      {
        let that = this;
        that.timer = false;
        let url = "/sys_openlookeng_cluster/v2/queryClusterItem";
        let userInfo = JSON.parse(localStorage.getItem('userInfo'))
        let obj = {'code': userInfo.id}
        doGet(url, obj).then(res =>
        {
          this.loadingData=false;
          if(!res.data.data)
          {
            that.$router.push('/guide');
          }
          if (res.data.code === 0)
          {
            let data = res.data.data;
            that.essentialInformation = data;
            that.essentialInformation.clusterName=data.clusterName;
            that.essentialInformation.cpu = data.useCpu + "Core/" + data.totalCpu + "Core";
            that.essentialInformation.memory = data.useRam + "G/" + data.totalRam + "G";
            that.essentialInformation.example = "运行中 " + data.nodeRunNum + "/停止 " + data.nodecloseNum;
            that.roleData=[];
            if (data.nodeItem && (JSON.stringify(data.nodeItem) != 'Object { }'))
            {
              Object.keys(data.nodeItem).forEach(key =>
              {
                let value = data.nodeItem[key]
                let obj = {
                  'name': key,
                  'run': value["运行中"],
                  'close': value["关闭"]
                };
                that.roleData.push(obj);
              })
            }
          }
          setTimeout(()=>
          {
            that.timer = true;
          },1000)
        });
      },
      queryClusterItem2()
      {
        let that = this;
        that.timer = false;
        let url = "/sys_openlookeng_cluster/v2/queryClusterItem";
        let userInfo = JSON.parse(localStorage.getItem('userInfo'))
        let obj = {'code': userInfo.id}
        doGet(url, obj).then(res =>
        {
          if(!res.data.data)
          {
            that.$router.push('/guide');
          }
          if (res.data.code === 0)
          {
            let data = res.data.data;
            that.essentialInformation = data;
            that.essentialInformation.clusterName=data.clusterName;
            that.essentialInformation.cpu = data.useCpu + "Core/" + data.totalCpu + "Core";
            that.essentialInformation.memory = data.useRam + "G/" + data.totalRam + "G";
            that.essentialInformation.example = "运行中 " + data.nodeRunNum + "/停止 " + data.nodecloseNum;
            that.roleData=[];
            if (data.nodeItem && (JSON.stringify(data.nodeItem) != 'Object { }'))
            {
              Object.keys(data.nodeItem).forEach(key =>
              {
                let value = data.nodeItem[key]
                let obj = {
                  'name': key,
                  'run': value["运行中"],
                  'close': value["关闭"]
                };
                that.roleData.push(obj);
              })
            }
          }
          setTimeout(()=>
          {
            that.timer = true;
          },1000)
        });
      },
      changeTime()
      {
        this.cpuResultList=[];
        this.memoryResultList=[];
      },
      initMemoryUsage(echartData)
      {
        let that=this;
        let option =
        {
          tooltip: {
            trigger: 'axis',
          },
          xAxis: {
            type: 'category',
            boundaryGap:false,
            axisLabel:
            {
              interval:1,
              formatter:function(value)
              {
                return value.slice(0,11)+"\n"+value.slice(11)
              }
            },
            splitLine: {
              show: false
            }
          },
          yAxis: {
            name:'(单位%)',
            type: 'value',
            max:100
          },
          series: [
            {
              data:echartData,
              type: 'line',
              showSymbol: false,
            }
          ]
        }
        new Promise((resolve)=>{resolve();}).then(()=>
        {
          that.memoryEcharts.setOption(option);
        })
      },
      initCpuUtilization(echartData)
      {
        let that=this;
        let option =
        {
          tooltip: {
            trigger: 'axis',
          },
          xAxis: {
            type: 'category',
            boundaryGap:false,
            axisLabel:
            {
              interval:1,
              formatter:function(value)
              {
                return value.slice(0,11)+"\n"+value.slice(11)
              }
            },
            splitLine: {
              show: false
            }
          },
          yAxis: {
            name:'(单位%)',
            type: 'value',
            max:100
          },
          series: [
            {
              data:echartData,
              type: 'line',
              showSymbol: false,
            }
          ]
        }
        new Promise((resolve)=>{resolve();}).then(()=>
        {
          that.cpuEcharts.setOption(option);
        })
      },
      getEchartsData()
      {
        this.cpuResultList=[]
        this.memoryResultList=[]
        let that = this;
        let url = "/sys_ecs/clusterEchartInfo";
        let obj =
        {
          'nodeId':-1,
          queryType:this.time
        }
        doGet(url, obj).then(res =>
        {
          if(res.data.code==0)
          {
            that.initCpuUtilization(that.formatEchartsData(that.cpuResultList,res.data.data.cpuInfoList));
            that.initMemoryUsage(that.formatEchartsData(that.memoryResultList,res.data.data.menInfoList));
          }
        })
      },
      formatEchartsData(list,arr)
      {
        if(list.length==0)
        {
          for(let i=0;i<arr.length;i++)
          {
            list.push([arr[i].time,arr[i].value])
          }
        }
        else
        {
          list.splice(0,1);
          list.push([arr[arr.length-1].time,arr[arr.length-1].value])
        }
        return list
      },
      selectTimeChange(e) {},
      operation(e)
      {
        // this.loadingData = true;
        //start  stop  upgrade uninstall uninstall
        if (e == 'start' || e == 'stop' || e == 'restart')
        {
          this.changeClassState(e);
        }
        else if (e == 'uninstall')
        {
          this.dialogVisible = true;
        }
        if(e == 'upgrade')
        {
          this.updateStated = true;
          this.value = "";
        }
      },
      // get upgrade version
      updatePackageList(way)
      {
        if (way)
        {
          let url = '/sys_file/listFileNoPage?upgradeWay=' + way
          doGet(url).then(res =>
          {
            if (res.data.code == 0)
            {
              this.updatepackageFileList = res.data.data
            }
          })
        }
      },
      //upgrade version
      updateState()
      {
        if(this.updategradeWay == "") return this.$message('请选择安装方式')
        if(this.updatefileId == "")
        {
          if(this.updategradeWay==2)
          {
            return this.$message('请选择安装包')
          }
          else
          {
            return this.$message('请选择版本号')
          }
        }
        let dataObj=
        {
          fileId:this.updatefileId,
          isStart:true,
          nodeIds:[],
        }
        this.updateloading = true;
        let url = "/sys_openlookeng_cluster/updateClusterVersion";
        doPost(url,dataObj).then(res=>
        {
          this.updateloading = false;
          if(res.data.code == 0) {
            this.updateStated = false;
            this.loadingData=false;
            this.$message({
              message:'操作成功',
              type: 'success'
            });
          };
          pubsub.publish("shuaxin","shilie")
        })
      },

      //start,shut down,restart cluster
      changeClassState(state)
      {
        let that=this;
        this.loading = true;
        this.loadingData = true;
        let obj =
        {
          'state': state,
          'nodeIds': []
        };
        let url = '/sys_openlookeng_cluster/changeClassState';
        doPost(url, obj).then(res =>
        {
          that.loading = false;
          that.loadingData = false;
          that.value = '';
          if (res.data.code == 0)
          {
            that.$message.success(res.data.msg);
          }
        });
      },
      handleClick(tab, event)
      {
        this.first=tab.name;
        // console.log(tab.name)
        if (tab.name == 'gl')
        {
          this.tabName = '概览'
        }
        if (tab.name == 'slqk')
        {
          this.tabName = '实例';
          pubsub.publish("role",false)
        }
        if (tab.name == 'pz')
        {
          this.tabName = '配置';
          pubsub.publish("role",true)
        }
      },
    },
    computed:
    {
      showCpu() {
        return this.chart.length == 0 || this.chart.indexOf("cpu") !== -1
      },
      showMemory() {
        return this.chart.length == 0 || this.chart.indexOf("memory") !== -1
      },
    },
  }
</script>


<style>
  .btn {
    color: #409EFF;
    border-color: #409EFF;
  }

  .color {
    color: #999999;

  }

  .row {
    height: 28px;
    margin-top: 5px;
    line-height: 28px;
    font-size: 13px;
  }

  .font {
    font-size: 13px;
    line-height: 28px;
  }
</style>

<style scoped>
  .updateFont{
    letter-spacing: 1.5px;
  }
  .updateFont2{
    letter-spacing: 8px;
  }
  .installBtns{
    margin-left: 63%;
  }
    .installPackage,.installBtns{
    margin-top: 20px;
  }
  .shangchuanSty {
    color: #409EFF;
    font-size: 28px !important;
    cursor: pointer;
    padding-left: 10px;
  }
</style>
